import os
import shutil
import json
import csv
import argparse


def process_csv_and_copy_files(root_dir, csv_file_path):
    # 确保根目录存在
    if not os.path.exists(root_dir):
        os.makedirs(root_dir)

    # 读取CSV文件
    with open(csv_file_path, mode='r', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)

        for row in reader:
            source_operation_code = row['source_operation_code']
            source_operation_id = row['source_operation_id']
            source_sysfilename = row['source_sysfilename']
            source_phyfilename = row['source_phyfilename']
            source_file_not_found_path = row['source_file_not_found_path']
            find_absolute_path = row['find_absolute_path']

            # 创建目录路径
            dir_path = os.path.join(root_dir, source_operation_code, source_sysfilename.rsplit('.', 1)[0])
            os.makedirs(dir_path, exist_ok=True)

            # 创建TXT文件并写入JSON数据
            txt_file_path = os.path.join(dir_path, f'{source_phyfilename}.txt')
            json_data = {
                'source_operation_code': source_operation_code,
                'source_operation_id': source_operation_id,
                'source_sysfilename': source_sysfilename,
                'source_phyfilename': source_phyfilename,
                'source_file_not_found_path': source_file_not_found_path,
                'find_absolute_path': find_absolute_path
            }
            with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
                json.dump(json_data, txt_file, ensure_ascii=False, indent=4)

            # 拷贝文件到创建的目录中
            try:
                if os.path.isfile(find_absolute_path):
                    shutil.copy(find_absolute_path, dir_path)
                else:
                    print(f"Warning: File '{find_absolute_path}' does not exist and cannot be copied.")
            except Exception as e:
                print(f"Error while copying file '{find_absolute_path}': {e}")


if __name__ == "__main__":
    # 设置命令行参数解析
    parser = argparse.ArgumentParser(description='Process CSV and copy files based on CSV data.')
    parser.add_argument('--root_dir', type=str, required=True,
                        help='Root directory where folders and files will be created.')
    parser.add_argument('--csv_file', type=str, required=True, help='Path to the CSV file containing the data.')

    # 解析命令行参数
    args = parser.parse_args()

    # 调用函数
    process_csv_and_copy_files(args.root_dir, args.csv_file)
